package cn.xshi.bpm.util.message;

import cn.xshi.bpm.util.message.vo.MailDTO;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.springframework.mail.MailException;

import java.util.Properties;

/**
 * @Desc 工作流邮件体醒
 * @Author 邓纯杰
 * @CreateTime 2012-12-12 12:12:12
 */
@Component
@Slf4j
@Data
public class MailService {

    @Value("${jehc.mail.host:smtp.qq.com}")
    private String host;

    @Value("${jehc.mail.userName:}")
    private String userName;

    @Value("${jehc.mail.password:}")
    private String password;

    @Value("${jehc.mail.port:465}")
    private Integer port;

    @Value("${jehc.mail.smtp.auth:false}")
    private Boolean auth;

    @Value("${jehc.mail.smtp.ssl.enable:false}")
    private Boolean ssl;

    /**
     *
     * @param mailDTO
     */
    public void send(MailDTO mailDTO){
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        setJavaMailSenderConfig(mailSender);
        MimeMessage message= mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper=new MimeMessageHelper(message, true, "UTF-8");
            helper.setFrom(userName);
            helper.setTo(mailDTO.getTos().toArray(new String[]{}));
            helper.setSubject(mailDTO.getSubject());
            helper.setText(mailDTO.getHtml(),true);
            mailSender.send(message);
        } catch (MailException e) {
            log.error("邮件发送异常,MailException：{}",e);
        } catch (MessagingException e) {
            log.error("邮件发送异常,MessagingException：{}",e);
        }
    }

    /**
     * 配置
     * @param mailSender
     */
    private void setJavaMailSenderConfig(JavaMailSenderImpl mailSender){
        mailSender.setHost(host);//邮件服务器ip
        mailSender.setUsername(userName);//登录名
        mailSender.setPassword(password);//密码
        mailSender.setDefaultEncoding("Utf-8");
//        mailSender.setPort(port);//端口号
        Properties pro = new Properties();
    	pro.put("mail.smtp.auth", auth);
    	if(ssl){
            pro.put("mail.smtp.ssl.enable", ssl);//使用SSL端口
            pro.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        }
        pro.setProperty("mail.smtp.socketFactory.port", "587");
    	mailSender.setJavaMailProperties(pro);
    }
}
